package com.yellow.car.task;

import com.yellow.car.api.DispatchApi;
import com.yellow.car.api.StationApi;
import com.yellow.car.entity.CyclingTruckCar;
import com.yellow.car.entity.Station;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@EnableScheduling
@Slf4j
public class TruckTask {
    @Resource
    StationApi stationApi;
    @Resource
    DispatchApi dispatchApi;

    @Scheduled(cron = "0/1 * * * * ?")
    private void truckDispatch() {
        //检查站点小黄车数量,是否要调度
        Station stationA = stationApi.getStationInfoByName("A");
        Station stationB = stationApi.getStationInfoByName("B");
        Station stationC = stationApi.getStationInfoByName("C");
        List<Station> stationList = new ArrayList<>();
        stationList.add(stationA);
        stationList.add(stationB);
        stationList.add(stationC);
        //排序
        stationList = stationList.stream().sorted(Comparator.comparing(Station::getCarNum)).collect(Collectors.toList());
        if (stationList.get(0).getCarNum() > 15) {
            log.info("最小站点还有15辆车,不需要调度");
            return;
        }
        //开始调度
        dispatchApi.dispatch(stationList.get(stationList.size() - 1), stationList.get(0), 100, 3);
    }

    @Scheduled(cron = "0/1 * * * * ?")
    private void truckCycling() {
        //检查运输途中的货车是否到站
        List<CyclingTruckCar> cyclingTruckCarList = dispatchApi.getCyclingTruckList();
        if (CollectionUtils.isEmpty(cyclingTruckCarList)) {
            log.info("没有运输中的货车");
            return;
        }
        long currentTime = System.currentTimeMillis();
        cyclingTruckCarList = cyclingTruckCarList.stream().filter(x -> x.getCyclingEndTime() >= currentTime).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cyclingTruckCarList)) {
            log.info("运输中的货车还没有到站");
            return;
        }
        cyclingTruckCarList.forEach(this::invoke);
    }

    private void invoke(CyclingTruckCar cyclingTruckCar) {
        Boolean trunkFlag = stationApi.addTruckByStationName(cyclingTruckCar.getEndStationName(), cyclingTruckCar.getTruck());
        Boolean carFlag = stationApi.addByStationName(cyclingTruckCar.getEndStationName(), cyclingTruckCar.getYellowCarNum());
        if (trunkFlag && carFlag) {
            dispatchApi.removeCyclingTruckList(cyclingTruckCar);
        } else {
            log.info("移除运输中的货车信息失败,人工干预调整数据,或者事务回滚类似操作,cyclingTruckCar:{},trunkFlag:{},carFlag:{}", cyclingTruckCar, trunkFlag, carFlag);
        }
    }
}
